# coding : utf-8
from flask import render_template , url_for , request , flash , session, redirect , g , send_file
import os
import datetime

def init_views(app):

    @app.route('/')
    def index():
        return render_template('index.html')

    @app.route('/login',methods=['GET','POST'])
    def login():
        if request.method == 'POST':
            session['username'] = request.form['username']
            session['class'] = request.form['class']
            if session['username'] == app.config['USERNAME'] and session['class']==app.config['PASSWORD']:
                return redirect(url_for('list'))

            cur = g.db.execute('select name,class from entries where name==?',[session['username']])
            for row in cur:
                if row[0] == session['username']:
                    flash('You have already logged in!')
                    return redirect(url_for('list'))
                else:
                    break

            g.db.execute('insert into entries (name,class) values(?,?)',[request.form['username'],request.form['class']])
            g.db.commit()

            flash('login successful!')
            return redirect(url_for('index'))
        return render_template('login.html')

    @app.route('/logout')
    def logout():
        session.pop('username',None)
        flash('log out successful!')
        return redirect(url_for('index'))

    @app.route('/list')
    def list():
        flag=True
        if 'username' in session: 
            if session['username'] != app.config['USERNAME'] : 
                flag=False
        else:
            flag=False

        tot=1
        cur = g.db.execute('select name,class from entries order by class desc')

        entires = []

        for row in cur.fetchall():
            d = {"name":row[0],"Class":row[1]}
            if d in entires:
                continue
            elif d['name']==None:
                continue
            else:
                entires.append(d)
                tot=tot+1

        tot=0

        for row in entires : 
            tot=tot+1
            row['id']=tot
        #entires = [dict(name=row[0],Class=row[1]) for row in cur.fetchall()]
        #tot=len(entires)
        return render_template('list.html',List=entires,flag=flag,Sum=tot)

    @app.route('/change/<user>',methods=['POST'])
    def change(user):
        g.db.execute('delete from entries where name==?',[user])
        g.db.commit()
        flash('Change successful!')
        return redirect(url_for('list'))

    @app.route('/change_all',methods=['POST'])
    def change_all():
        g.db.execute('delete from entries')
        g.db.commit()
        return redirect(url_for('list'))

    @app.route('/download',methods = ['GET','POST'])
    def download():

        pwd = os.getcwd()

        now = datetime.datetime.now()

        now = now.strftime('%Y-%m-%d %H:%M:%S')

        pwd = os.path.join( pwd,'download','%s_list.txt' % now )

        file = open(pwd,'w')

        tot=0
        cur = g.db.execute('select name,class from entries order by class desc')

        entires = []

        for row in cur.fetchall():
            d = {"name":row[0],"Class":row[1]}
            if d in entires:
                continue
            elif d['name']==None:
                continue
            else:
                entires.append(d)

        file.write("Id,Name,Class\n")

        for i in entires:
            tot=tot+1
            s = "%d %s %s\n" % (tot,i['name'],i['Class'])
            file.write(s)

        file.close()

        return send_file(pwd)
